<template>
  <view class="page-container" :class="themeClass">
    <!-- 自定义导航栏 -->
    <CustomNavBar 
      title="日记筛选" 
      :show-back="true"
    />
    
    <!-- 页面内容 -->
    <view class="page-content">
      <scroll-view scroll-y class="filter-scroll">
        <!-- 筛选条件 -->
        <view class="filter-section">
          <view class="section-title">
            <text class="title-text">筛选条件</text>
            <button class="reset-btn" @click="resetFilters">重置</button>
          </view>
          
          <!-- 日期筛选 -->
          <view class="filter-group">
            <view class="group-title">
              <text class="group-icon">📅</text>
              <text class="group-text">日期范围</text>
            </view>
            
            <view class="date-filter">
              <view class="date-item" @click="selectStartDate">
                <text class="date-label">开始日期</text>
                <text class="date-value" :class="{ placeholder: !filters.startDate }">
                  {{ filters.startDate || '选择开始日期' }}
                </text>
              </view>
              
              <view class="date-separator">
                <text class="separator-text">至</text>
              </view>
              
              <view class="date-item" @click="selectEndDate">
                <text class="date-label">结束日期</text>
                <text class="date-value" :class="{ placeholder: !filters.endDate }">
                  {{ filters.endDate || '选择结束日期' }}
                </text>
              </view>
            </view>
          </view>
          
          <!-- 标签筛选 -->
          <view class="filter-group">
            <view class="group-title">
              <text class="group-icon">🏷️</text>
              <text class="group-text">标签筛选</text>
            </view>
            
            <view class="tag-filter">
              <view class="tag-list" v-if="tags.length > 0">
                <view 
                  class="tag-item"
                  v-for="tag in tags"
                  :key="tag.id"
                  :class="{ active: filters.tagIds.includes(tag.id) }"
                  @click="toggleTag(tag.id)"
                >
                  <text class="tag-name">{{ tag.name }}</text>
                </view>
              </view>
              
              <view class="empty-state" v-else>
                <text class="empty-text">暂无标签</text>
                <button class="create-tag-btn" @click="goToTagManage">
                  <text class="btn-text">创建标签</text>
                </button>
              </view>
            </view>
          </view>
          
          <!-- 分类筛选 -->
          <view class="filter-group">
            <view class="group-title">
              <text class="group-icon">📂</text>
              <text class="group-text">分类筛选</text>
            </view>
            
            <view class="category-filter">
              <view class="category-list" v-if="categories.length > 0">
                <view 
                  class="category-item"
                  v-for="category in categories"
                  :key="category.id"
                  :class="{ active: filters.categoryId === category.id }"
                  @click="toggleCategory(category.id)"
                >
                  <view class="category-icon" :style="{ backgroundColor: category.color + '20' }">
                    <text class="icon-text">{{ category.icon || '📁' }}</text>
                  </view>
                  <text class="category-name">{{ category.name }}</text>
                </view>
              </view>
              
              <view class="empty-state" v-else>
                <text class="empty-text">暂无分类</text>
                <button class="create-category-btn" @click="goToCategoryManage">
                  <text class="btn-text">创建分类</text>
                </button>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 操作按钮 -->
        <view class="action-section">
          <button class="search-btn" @click="searchDiaries" :disabled="searching">
            <text class="btn-icon">🔍</text>
            <text class="btn-text">{{ searching ? '搜索中...' : '搜索日记' }}</text>
          </button>
        </view>
        
        <!-- 搜索结果 -->
        <view class="result-section" v-if="searchPerformed">
          <view class="result-header">
            <text class="result-title">搜索结果</text>
            <text class="result-count">共找到 {{ filteredDiaries.length }} 篇日记</text>
          </view>
          
          <!-- 导出按钮 -->
          <view class="export-section" v-if="filteredDiaries.length > 0">
            <button class="export-btn" @click="exportToPDF" :disabled="exporting">
              <text class="btn-icon">📄</text>
              <text class="btn-text">{{ exporting ? '导出中...' : '导出为PDF' }}</text>
            </button>
          </view>
          
          <!-- 日记列表 -->
          <view class="diary-list" v-if="filteredDiaries.length > 0">
            <view 
              class="diary-item"
              v-for="diary in filteredDiaries"
              :key="diary.id"
              @click="goToDiaryDetail(diary.id)"
            >
              <view class="diary-header">
                <text class="diary-title">{{ diary.title || '无标题' }}</text>
                <text class="diary-date">{{ formatDate(diary.diaryDate) }}</text>
              </view>
              
              <view class="diary-content">
                <text class="content-preview">{{ getContentPreview(diary.content) }}</text>
              </view>
              
              <view class="diary-meta">
                <view class="category-info" v-if="diary.category">
                  <view class="category-dot" :style="{ backgroundColor: diary.category.color }"></view>
                  <text class="category-text">{{ diary.category.name }}</text>
                </view>
                
                <view class="tag-info" v-if="diary.tags && diary.tags.length > 0">
                  <text class="tag-label">标签:</text>
                  <text class="tag-text">{{ diary.tags.map(t => t.name).join(', ') }}</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 空状态 -->
          <view class="empty-result" v-else>
            <text class="empty-icon">📝</text>
            <text class="empty-title">未找到匹配的日记</text>
            <text class="empty-desc">请尝试调整筛选条件</text>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 日期选择器 -->
    <picker 
      v-if="showStartDatePicker"
      mode="date"
      :value="filters.startDate"
      @change="onStartDateChange"
      @cancel="showStartDatePicker = false"
    >
      <view></view>
    </picker>
    
    <picker 
      v-if="showEndDatePicker"
      mode="date"
      :value="filters.endDate"
      @change="onEndDateChange"
      @cancel="showEndDatePicker = false"
    >
      <view></view>
    </picker>
    
    <!-- 加载状态 -->
    <view class="loading-overlay" v-if="loading">
      <text class="loading-text">⏳</text>
      <text class="loading-desc">加载中...</text>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/store/user'
import { getDiariesAPI } from '@/api/diary'
import { getCategoriesAPI } from '@/api/category'
import { getTagsAPI } from '@/api/tag'
import { formatDate, extractResponseData } from '@/utils/index'
import CustomNavBar from '@/components/CustomNavBar.vue'

export default {
  name: 'DiaryFilter',
  components: {
    CustomNavBar
  },
  setup() {
    const userStore = useUserStore()
    
    return {
      userStore,
      formatDate
    }
  },
  data() {
    return {
      loading: false,
      searching: false,
      exporting: false,
      searchPerformed: false,
      showStartDatePicker: false,
      showEndDatePicker: false,
      
      filters: {
        startDate: '',
        endDate: '',
        tagIds: [],
        categoryId: null
      },
      
      tags: [],
      categories: [],
      filteredDiaries: []
    }
  },
  
  computed: {
    themeClass() {
      return this.userStore.themeMode === 'dark' ? 'theme-dark' : 'theme-light'
    }
  },
  
  onLoad() {
    this.initPage()
  },
  
  methods: {
    async initPage() {
      if (!this.userStore.checkLoginStatus()) return
      
      this.loading = true
      try {
        await Promise.all([
          this.loadTags(),
          this.loadCategories()
        ])
      } catch (error) {
        console.error('初始化页面失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    async loadTags() {
      try {
        const res = await getTagsAPI()
        const data = extractResponseData(res)
        this.tags = data || []
      } catch (error) {
        console.error('加载标签失败:', error)
      }
    },
    
    async loadCategories() {
      try {
        const res = await getCategoriesAPI()
        const data = extractResponseData(res)
        this.categories = data || []
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },
    
    // 日期选择
    selectStartDate() {
      this.showStartDatePicker = true
    },
    
    selectEndDate() {
      this.showEndDatePicker = true
    },
    
    onStartDateChange(e) {
      this.filters.startDate = e.detail.value
      this.showStartDatePicker = false
    },
    
    onEndDateChange(e) {
      this.filters.endDate = e.detail.value
      this.showEndDatePicker = false
    },
    
    // 标签切换
    toggleTag(tagId) {
      const index = this.filters.tagIds.indexOf(tagId)
      if (index > -1) {
        this.filters.tagIds.splice(index, 1)
      } else {
        this.filters.tagIds.push(tagId)
      }
    },
    
    // 分类切换
    toggleCategory(categoryId) {
      if (this.filters.categoryId === categoryId) {
        this.filters.categoryId = null
      } else {
        this.filters.categoryId = categoryId
      }
    },
    
    // 重置筛选条件
    resetFilters() {
      this.filters = {
        startDate: '',
        endDate: '',
        tagIds: [],
        categoryId: null
      }
      this.searchPerformed = false
      this.filteredDiaries = []
    },
    
    // 搜索日记
    async searchDiaries() {
      // 验证筛选条件
      if (!this.filters.startDate && !this.filters.endDate && 
          this.filters.tagIds.length === 0 && !this.filters.categoryId) {
        uni.showToast({
          title: '请至少选择一个筛选条件',
          icon: 'none'
        })
        return
      }
      
      this.searching = true
      try {
        const params = {
          page: 1,
          limit: 1000 // 获取所有匹配的日记
        }
        
        // 添加日期筛选
        if (this.filters.startDate) {
          params.startDate = this.filters.startDate
        }
        if (this.filters.endDate) {
          params.endDate = this.filters.endDate
        }
        
        // 添加标签筛选
        if (this.filters.tagIds.length > 0) {
          params.tagIds = this.filters.tagIds.join(',')
        }
        
        // 添加分类筛选
        if (this.filters.categoryId) {
          params.categoryId = this.filters.categoryId
        }
        
        const res = await getDiariesAPI(params)
        const data = extractResponseData(res)
        
        this.filteredDiaries = data.list || []
        this.searchPerformed = true
        
        uni.showToast({
          title: `找到 ${this.filteredDiaries.length} 篇日记`,
          icon: 'success'
        })
        
      } catch (error) {
        console.error('搜索日记失败:', error)
        uni.showToast({
          title: '搜索失败',
          icon: 'none'
        })
      } finally {
        this.searching = false
      }
    },
    
    // 导出为PDF
    async exportToPDF() {
      if (this.filteredDiaries.length === 0) {
        uni.showToast({
          title: '没有可导出的日记',
          icon: 'none'
        })
        return
      }
      
      this.exporting = true
      try {
        // 这里可以集成PDF生成库，比如jsPDF
        // 暂时用模拟的方式
        await this.generatePDF()
        
        uni.showToast({
          title: 'PDF导出成功',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('导出PDF失败:', error)
        uni.showToast({
          title: '导出失败',
          icon: 'none'
        })
      } finally {
        this.exporting = false
      }
    },
    
    // 生成PDF（模拟）
    async generatePDF() {
      return new Promise((resolve, reject) => {
        // 模拟PDF生成过程
        setTimeout(() => {
          try {
            // 构建导出内容
            let content = `日记筛选结果导出\n\n`
            content += `导出时间: ${formatDate(new Date())}\n`
            content += `筛选条件:\n`
            
            if (this.filters.startDate) {
              content += `- 开始日期: ${this.filters.startDate}\n`
            }
            if (this.filters.endDate) {
              content += `- 结束日期: ${this.filters.endDate}\n`
            }
            if (this.filters.tagIds.length > 0) {
              const selectedTags = this.tags.filter(t => this.filters.tagIds.includes(t.id))
              content += `- 标签: ${selectedTags.map(t => t.name).join(', ')}\n`
            }
            if (this.filters.categoryId) {
              const selectedCategory = this.categories.find(c => c.id === this.filters.categoryId)
              content += `- 分类: ${selectedCategory?.name || ''}\n`
            }
            
            content += `\n共找到 ${this.filteredDiaries.length} 篇日记:\n\n`
            
            // 添加日记内容
            this.filteredDiaries.forEach((diary, index) => {
              content += `${index + 1}. ${diary.title || '无标题'}\n`
              content += `日期: ${diary.diaryDate}\n`
              if (diary.category) {
                content += `分类: ${diary.category.name}\n`
              }
              if (diary.tags && diary.tags.length > 0) {
                content += `标签: ${diary.tags.map(t => t.name).join(', ')}\n`
              }
              content += `内容: ${this.getContentPreview(diary.content)}\n\n`
            })
            
            console.log('PDF内容生成完成:', content.substring(0, 200) + '...')
            
            // 在实际项目中，这里可以调用PDF生成库
            // 例如：jsPDF 或其他第三方库
            
            resolve(content)
          } catch (error) {
            reject(error)
          }
        }, 2000)
      })
    },
    
    // 获取内容预览
    getContentPreview(content) {
      if (!content) return '无内容'
      // 去除HTML标签和换行符，截取前50个字符
      const plainText = content.replace(/<[^>]*>/g, '').replace(/\n/g, ' ')
      return plainText.length > 50 ? plainText.substring(0, 50) + '...' : plainText
    },
    
    // 跳转到日记详情
    goToDiaryDetail(diaryId) {
      uni.navigateTo({
        url: `/pages/diary/detail?id=${diaryId}`
      })
    },
    
    // 跳转到标签管理
    goToTagManage() {
      uni.navigateTo({
        url: '/pages/tag/list'
      })
    },
    
    // 跳转到分类管理
    goToCategoryManage() {
      uni.switchTab({
        url: '/pages/category/list'
      })
    }
  }
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  transition: background-color 0.3s ease;
}

.page-content {
  padding: 40rpx;
  padding-top: calc(var(--status-bar-height, 44rpx) + 88rpx + 40rpx);
  min-height: calc(100vh - calc(var(--status-bar-height, 44rpx) + 88rpx));
}

.filter-scroll {
  height: 100%;
}

.filter-section {
  border-radius: 24rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.reset-btn {
  border-radius: 16rpx;
  padding: 12rpx 24rpx;
  font-size: 24rpx;
  border: none;
}

.reset-btn::after {
  border: none;
}

.reset-btn:active {
  background-color: #e8e8e8;
}

.filter-group {
  margin-bottom: 40rpx;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.group-title {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 24rpx;
}

.group-icon {
  font-size: 28rpx;
}

.group-text {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
}

.date-filter {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.date-item {
  flex: 1;
  border-radius: 16rpx;
  padding: 24rpx;
  text-align: center;
  transition: background-color 0.2s;
}

.date-item:active {
  background-color: #e9ecef;
}

.date-label {
  font-size: 24rpx;
  color: #666666;
  display: block;
  margin-bottom: 8rpx;
}

.date-value {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

.date-value.placeholder {
  color: #999999;
}

.date-separator {
  display: flex;
  align-items: center;
  justify-content: center;
}

.separator-text {
  font-size: 24rpx;
  color: #666666;
}

.tag-filter,
.category-filter {
  min-height: 80rpx;
}

.tag-list,
.category-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.tag-item {
  border: 2rpx solid transparent;
  border-radius: 24rpx;
  padding: 16rpx 24rpx;
  transition: all 0.2s;
}

.tag-item.active {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.tag-name {
  font-size: 26rpx;
  color: #333333;
}

.tag-item.active .tag-name {
  color: #1890ff;
  font-weight: 500;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  border: 2rpx solid transparent;
  border-radius: 16rpx;
  padding: 16rpx 20rpx;
  margin-right: 16rpx;
  margin-bottom: 16rpx;
  transition: all 0.2s;
}

.category-item.active {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.category-icon {
  width: 48rpx;
  height: 48rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-text {
  font-size: 24rpx;
}

.category-name {
  font-size: 26rpx;
  color: #333333;
}

.category-item.active .category-name {
  color: #1890ff;
  font-weight: 500;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;
  padding: 40rpx;
}

.empty-text {
  font-size: 26rpx;
  color: #999999;
}

.create-tag-btn,
.create-category-btn {
  background-color: #1890ff;
  color: #ffffff;
  border-radius: 16rpx;
  padding: 12rpx 24rpx;
  font-size: 24rpx;
  border: none;
}

.create-tag-btn::after,
.create-category-btn::after {
  border: none;
}

.action-section {
  margin-bottom: 40rpx;
}

.search-btn {
  width: 100%;
  background-color: #1890ff;
  color: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  border: none;
  font-size: 32rpx;
  font-weight: 500;
}

.search-btn::after {
  border: none;
}

.search-btn:disabled {
  background-color: #cccccc;
  color: #999999;
}

.btn-icon {
  font-size: 28rpx;
}

.btn-text {
  font-size: 28rpx;
}

.result-section {
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
}

.result-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.result-count {
  font-size: 26rpx;
  color: #666666;
}

.export-section {
  margin-bottom: 32rpx;
}

.export-btn {
  width: 100%;
  background-color: #52c41a;
  color: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  border: none;
  font-size: 28rpx;
}

.export-btn::after {
  border: none;
}

.export-btn:disabled {
  background-color: #cccccc;
  color: #999999;
}

.diary-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.diary-item {
  border-radius: 16rpx;
  padding: 24rpx;
  transition: background-color 0.2s;
}

.diary-item:active {
  background-color: #e9ecef;
}

.diary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.diary-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
  flex: 1;
}

.diary-date {
  font-size: 24rpx;
  color: #666666;
}

.diary-content {
  margin-bottom: 16rpx;
}

.content-preview {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.5;
}

.diary-meta {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.category-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.category-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
}

.category-text {
  font-size: 24rpx;
  color: #666666;
}

.tag-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.tag-label {
  font-size: 24rpx;
  color: #999999;
}

.tag-text {
  font-size: 24rpx;
  color: #666666;
}

.empty-result {
  text-align: center;
  padding: 80rpx 40rpx;
}

.empty-icon {
  font-size: 120rpx;
  display: block;
  margin-bottom: 24rpx;
}

.empty-title {
  font-size: 32rpx;
  color: #333333;
  font-weight: 500;
  display: block;
  margin-bottom: 12rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #666666;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-text {
  font-size: 80rpx;
  color: #ffffff;
  margin-bottom: 16rpx;
}

.loading-desc {
  font-size: 28rpx;
  color: #ffffff;
}

/* 主题适配 */
/* 默认浅色主题 */
.page-container {
  background-color: #f5f5f5;
}

.filter-section,
.result-section {
  background-color: #ffffff;
}

.date-item,
.tag-item,
.category-item,
.diary-item {
  background-color: #f8f9fa;
}

.reset-btn {
  background-color: #f0f0f0;
  color: #666666;
}

/* 明确的浅色主题 */
.theme-light.page-container {
  background-color: #f5f5f5 !important;
}

.theme-light .filter-section,
.theme-light .result-section {
  background-color: #ffffff !important;
}

.theme-light .date-item,
.theme-light .tag-item,
.theme-light .category-item,
.theme-light .diary-item {
  background-color: #f8f9fa !important;
}

.theme-light .reset-btn {
  background-color: #f0f0f0 !important;
  color: #666666 !important;
}

/* 深色主题 */
.theme-dark.page-container {
  background-color: #1e1e1e !important;
}

.theme-dark .filter-section,
.theme-dark .result-section {
  background-color: #252526 !important;
}

.theme-dark .title-text,
.theme-dark .group-text,
.theme-dark .result-title,
.theme-dark .diary-title,
.theme-dark .empty-title {
  color: #e8e8e8 !important;
}

.theme-dark .date-value,
.theme-dark .tag-name,
.theme-dark .category-name {
  color: #e8e8e8 !important;
}

.theme-dark .date-value.placeholder,
.theme-dark .result-count,
.theme-dark .diary-date,
.theme-dark .content-preview,
.theme-dark .category-text,
.theme-dark .tag-text,
.theme-dark .empty-desc {
  color: #b3b3b3 !important;
}

.theme-dark .date-item,
.theme-dark .tag-item,
.theme-dark .category-item,
.theme-dark .diary-item {
  background-color: #404040 !important;
}

.theme-dark .date-item:active,
.theme-dark .diary-item:active {
  background-color: #505050 !important;
}

.theme-dark .tag-item.active,
.theme-dark .category-item.active {
  background-color: #1e3a5f !important;
  border-color: #1890ff !important;
}

.theme-dark .reset-btn {
  background-color: #404040 !important;
  color: #b3b3b3 !important;
}

.theme-dark .reset-btn:active {
  background-color: #505050 !important;
}
</style> 